/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package towerz.game.entity.hut;

import java.util.Hashtable;
import java.util.Vector;
import towerz.system.Utilities;
import towerz.system.xml.XmlNode;
import towerz.system.xml.XmlReaderWriter;

/**
 *
 * @author LegACy
 */
public class HutFactory {
	protected HutFactory() {
		//Initialize
		m_HutDictionary	= new Hashtable();

		//Load tower file
		XmlNode XML = XmlReaderWriter.getInstance().readFromXmlFile(Utilities.HUTDATA_FOLDER + "/data.xml");

		//For each child
		for (int i = 0; i < XML.getChildren().size(); i++) {
			//Get child
			XmlNode Child = (XmlNode)XML.getChildren().elementAt(i);

			//Check name
			if (Child.getNodeName().equals("hut")) {
				//Save to dictionary
				int Index = Integer.parseInt(Child.getAttribute("index"));
				if (Index >= 0) m_HutDictionary.put(new Integer(Index), new HutData(Child));
			}
		}
		
		//Load description
		m_DescriptionXML = XmlReaderWriter.getInstance().readFromXmlFile(Utilities.HUTDATA_FOLDER + "/desc.xml");
		loadDescription();
	}

	public synchronized static HutFactory instance() {
		//Create state manager if doesn't exist
		if (s_Instance == null) {
            s_Instance = new HutFactory();
        }

        return s_Instance;
	}
	
	public void loadDescription() {
		//For each child
		for (int i = 0; i < m_DescriptionXML.getChildren().size(); i++) {
			//Get child
			XmlNode Child = (XmlNode)m_DescriptionXML.getChildren().elementAt(i);

			//Check name
			if (Child.getNodeName().equals("hut")) {
				//Get data
				int Index		= Integer.parseInt(Child.getAttribute("index"));
				HutData Data	= getHutData(Index);
				
				//Reload if not null
				if (Data != null) Data.loadDescription(Child);
			}
		}
	}

	public int[] getBasicHuts() {
		//Create variables
		Vector Basics			= new Vector();
		boolean[] IsHutBasic	= new boolean[m_HutDictionary.size() + 1];
		for (int i = 0; i < IsHutBasic.length; i++) IsHutBasic[i] = true;
		
		//For each hut
		for (int i = 1; i < IsHutBasic.length; i++) {
			//Get upgrades
			int[] Upgrades = ((HutData)m_HutDictionary.get(new Integer(i))).getUpgrades();
			for (int j = 0; j < Upgrades.length; j++) {
				IsHutBasic[Upgrades[j]] = false;
			}
		}

		//Add basic huts
		for (int i = 1; i < IsHutBasic.length; i++) if (IsHutBasic[i]) Basics.addElement(new Integer(i));

		//Copy vector to array
		int[] HutArray = new int[Basics.size()];
		for (int i = 0; i < HutArray.length; i++) HutArray[i] = ((Integer)Basics.elementAt(i)).intValue();

		//Return array
		return HutArray;
	}

	public HutData getHutData(int index) {
		return (HutData)m_HutDictionary.get(new Integer(index));
	}

	//The only instance
	private static HutFactory s_Instance = null;

	//Dictionary
	protected XmlNode	m_DescriptionXML;
	protected Hashtable m_HutDictionary;

}
